package com.zhanglijie.theory.readwrite;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/14 0014 15:44
 */
public class FineTextData {
    private final char[] buffer;
   // private final MyReadWriteLock lock = new MyReadWriteLock();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
    ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    public FineTextData(int size){
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            this.buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        readLock.lock();
        try {
            return doRead();
        }finally {
            readLock.unlock();
        }
    }

    private char[] doRead()  {
        char[] chars = new char[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            chars[i] = buffer[i];
        }
        try {
            Thread.sleep(1000);
        }catch (Exception e){}
        return chars;
    }

    public void write(char newChar) throws InterruptedException {
        writeLock.lock();
        try {
            doWrite(newChar);
        }finally {
            writeLock.unlock();
        }
    }
    private void doWrite(char newChar){
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = newChar;
        }
        try {
            Thread.sleep(50);
        }catch (Exception e){}
    }
}
